import { routerRedux } from 'dva/router';
import pathToRegexp from 'path-to-regexp';
import { Modal } from 'antd-mobile';
import { registerDoctor, register as registerService, login as loginService, getValidCode } from '../services/register';
import { setLocalStorage } from '../utils/storage';

const alert = Modal.alert;
export default {
  namespace: 'register',
  state: {
    inviteDoctorUid: '',
    inviteType: 'doctor',
    channel: 'weixin',
    registerLoading: false,
  },
  reducers: {
    showRegisterLoading(state) {
      return {
        ...state,
        registerLoading: true,
      };
    },
    hideRegisterLoading(state) {
      return {
        ...state,
        registerLoading: false,
      };
    },
    initQueryParams(state, { payload }) {
      return {
        ...state,
        inviteDoctorUid: payload.inviteDoctorUid,
        inviteType: payload.inviteType,
        channel: payload.channel,
      };
    },
  },
  effects: {
    *register({
      payload,
    }, { put, call }) {
      let mobile = payload.value.mobile;
      mobile = mobile.trim().replace(/\s/g, '');
      const password = payload.value.password;
      const smsCode = payload.value.validCode;
      const inviteDoctorUid = payload.inviteDoctorUid;
      const inviteType = payload.inviteType;
      const channel = payload.channel;
      // const inviteDoctorUid = yield select(({ register }) => register.inviteDoctorUid);
      // const inviteType = yield select(({ register }) => register.inviteType);
      // const channel = yield select(({ register }) => register.channel);
      yield put({ type: 'showRegisterLoading' });
      const { err } = yield call(registerDoctor, {
        loginName: mobile,
        password,
        smsCode,
        inviteDoctorUid,
        inviteType,
        channel,
      });
      if (!err) {
        const { data } = yield call(loginService, {
          loginName: mobile,
          password,
        });
        const token = data.tokenData.access_token;
        setLocalStorage('access_token', token);
        yield put(routerRedux.push('/physicianAuth'));
      } else {
        err.json.then((errJson) => {
          if (errJson.errCode === 400101) {
            Modal.alert('', '用户已存在！点击下方按钮，下载9K医生APP并登录，补全您的医师信息', [
              { text: '前往二维码下载APP',
                onPress: () => {
                  window.location.href = '/showqrcode.html';
                },
                style: { fontWeight: 'bold' } },
            ]);
          } else {
            alert(errJson.errMessage);
          }
        });
      }
      yield put({ type: 'hideRegisterLoading' });
    },
    *patientRegister({
      payload,
    }, { put, call }) {
      let mobile = payload.value.mobile;
      mobile = mobile.trim().replace(/\s/g, '');
      // const password = payload.password;
      const smsCode = payload.value.validCode;
      const inviteDoctorUid = payload.inviteDoctorUid;
      const inviteType = payload.inviteType;
      const channel = payload.channel;
      // const inviteDoctorUid = yield select(({ register }) => register.inviteDoctorUid);
      // const inviteType = yield select(({ register }) => register.inviteType);
      // const channel = yield select(({ register }) => register.channel);
      yield put({ type: 'showRegisterLoading' });
      const { err } = yield call(registerService, {
        mobile,
        // password,
        smsCode,
        inviteDoctorUid,
        inviteType,
        channel,
      });
      if (!err) {
        window.location.href = '/showqrcode.html';
      } else {
        err.json.then(errJson => alert(errJson.errMessage));
      }
      yield put({ type: 'hideRegisterLoading' });
    },
    *sendSmsCode({
      payload,
    }, { call }) {
      const mobile = payload.trim().replace(/\s/g, '');
      const res = yield call(getValidCode, {
        mobile,
      });
      const { err } = res;
      if (err) {
        err.json.then(errJson => alert(errJson.errMessage));
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const matchDoctors = pathToRegexp('/doctors').exec(location.pathname);
        if (matchDoctors) {
          dispatch({
            type: 'initQueryParams',
            payload: location.query,
          });
        }
      });
    },
  },
};
